package net.zjitc.servlet.response;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

/**
 * @Author Administrator
 * @Date 2020/5/19 16:16
 * 响应response设置响应体
 *   1、获取字符输出流
 *   2、输出数据到页面
 **/
@WebServlet("/writerDemo")
public class WriterDemo extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
       /*解决response中文乱码： 要在获取流对象之前
       *   1、设置服务器的编码 utf-8
       *   2、告诉客户端浏览器用什么编码来解析展示数据（响应头） */
      /* resp.setCharacterEncoding("utf-8");
       resp.setHeader("Content-type","text/html;charset=utf-8");*/

       /* 这两条语句可以简化写成下面这条，它的功能还是上面2个*/
        resp.setContentType("text/html;charset=utf-8");

        /* 通过response对象得到字符输出流*/
        PrintWriter pw = resp.getWriter();
        /* 通过字符输出流，往页面写数据*/
        pw.write("<h1>Hi</h1>");
        pw.write("hello");
        pw.write("你好！");
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        this.doGet(req,resp);
    }
}
